<?php

namespace App\Http\Controllers;

use DB;
use Illuminate\Http\Request;
use Validator;

use Ptime3\Functions\JoinData;
use Ptime3\Functions\Queue;

class TeamUserController extends Controller
{

    public function index(Request $request, $teamId)
    {
        $input = $request->all();
        //参数检验
        $validator = Validator::make($input,
            [
                'user_id'     => 'required|min:1'
            ]
        );
        if($validator->fails())
            return $this::jsonResponse(true,$validator->messages(),"paramError");

        $userId = $input['user_id'];

        //团队信息
        $teamResult = DB::table("tm_team")
            ->select("leader_id","is_public")
            ->where("id",$teamId)->where("is_deleted",0)->first();
        if(empty($teamResult))
            return $this::jsonResponse(true,[],"团队不存在。");

        $leaderId = $teamResult->leader_id;
        $isPublic = $teamResult->is_public;

        //查找
    	$teamUserResult = DB::table("tm_team_user")
    		->select("tm_team_user.id AS user_id","tm_team_user.join_time","tm_team_user.state",
    			"tm_team_user.user_id AS id")
    		->where("tm_team_user.team_id",$teamId)
    		->where("tm_team_user.state","!=",-1)
            ->where("tm_team_user.is_deleted",false);

        if($isPublic && $userId != $leaderId) 
            $teamUserResult = $teamUserResult
                ->whereIn("tm_team_user.user_id",[$userId,$leaderId]);

        $teamUserResult = $teamUserResult
            ->orderBy("tm_team_user.state","DESC")
            ->orderBy("tm_team_user.id","ASC")
    		->get();

    	foreach ($teamUserResult as $key => $value) {
    		$value->is_leader   = ($leaderId == $value->id)?true:false;
            $value->could_opera = ($userId == $value->id || $userId == $leaderId)?true:false;
            switch ($value->state){
                case 0:
                    $value->state_message = "等待创建用户同意。";
                    break;
                case -2:
                    $value->state_message = "等待受邀用户同意。";
                    break;
                default:
                    $value->state_message = "";
                    break;
            }
    	}

        //聚合用户数据
        $teamUserResult = JoinData::user($teamUserResult);
        
    	return $this::jsonResponse(false,$teamUserResult);
    }

    public function store($aInformData = null, $teamId, $userId)
    {
        $teamUserResult = DB::table("tm_team_user")
            ->select("id","state")
            ->where("team_id",$teamId)->where("user_id",$userId)
            ->where("is_deleted",false)->first();

        if(!empty($teamUserResult)){
            if($teamUserResult->state == 1)
                return $this::jsonResponse(true,[],"成员已加入团队。");

            $teamUserId = $teamUserResult->id;
            DB::table("tm_team_user")->where("id",$teamUserId)
                ->update(["state"=>1,"join_time"=>date("Y-m-d H:i:s")]);    
        }else{
            $insertData = [
                "team_id"  =>$teamId,
                "user_id"  =>$userId,
                "state"    =>1,
                "join_time"=>date("Y-m-d H:i:s")
            ];
            $teamUserId = DB::table("tm_team_user")->insertGetId($insertData);
        }
        DB::table("tm_team")->where("id",$teamId)->increment("user_count");

        //发送欢迎通知
        $teamName = DB::table("tm_team")->where("id",$teamId)->value("name");
        $leaderId = DB::table("tm_team")->where("id",$teamId)->value("leader_id");
        if(!empty($teamResult)){
            $informData = [
                "title"     => "欢迎加入团队 ".$teamName,
                "app_id"    => env("TEAM_APP_ID"),
                "object"    => "team",
                "object_id" => $teamId,
                "sender_id" => $leaderId,
                "users"     =>[["user_id"=>$userId]],
                "is_notcare"=>true,
                "reply_opts"=>[["content"=>"好的"]]
            ];
            Queue::put("restapi",["post","inform","inform/send",$informData]);
        }

        //发送额外的通知
        if(!empty($aInformData))
            Queue::put("restapi",["post","inform","inform/send",$aInformData]);

        return $this::jsonResponse(false,$teamUserId);
    }

    public function destroy(Request $request, $teamId,$userId)
    {
        $input = $request->all();
        //参数检验
        $validator = Validator::make($input,
            [
                'user_id'     => 'required|min:1'
            ]
        );
        if($validator->fails())
            return $this::jsonResponse(true,$validator->messages(),"paramError");

        $loginUserId = $input["user_id"];

        $teamResult = DB::table("tm_team")
            ->select("leader_id","name")->where("id",$teamId)->where("is_deleted",false)->first();
        if(empty($teamResult))
            return $this::jsonResponse(true,[],"无此团队。");
        
        $teamLeaderId = $teamResult->leader_id;
        $teamName     = $teamResult->name;
        
        if($teamLeaderId == $userId)
            return $this::jsonResponse(true,[],"无法剔除团队创始人。");

        //主动退出或被动踢出
        if($loginUserId == $userId){
            $informUserId = $teamLeaderId;
            $informTitle  = "{{user:id:$userId:name}} 已退出 $teamName";
        }else{
            if($teamLeaderId != $loginUserId)
                return $this::jsonResponse(true,[],"无权剔除成员。");
            
            $informUserId = $userId;
            $informTitle = "您已被 $teamName 踢出";
        }

        //删除
        $teamUserResult  = DB::table("tm_team_user")
            ->where("team_id",$teamId)->where("user_id",$userId)->update(["is_deleted"=>true]);
        if(!$teamUserResult)
            return $this::jsonResponse(true,[],"成员不存在。");
        
        DB::table("tm_team")->where("id",$teamId)->decrement("user_count");

        //删除通知集
        $setData = ["object"=>"team","object_id"=>$teamId];
        Queue::put("restapi",["delete","inform","set/user/$userId",$setData]);

        //发送通知
        $informData = [
            "title"     => $informTitle,
            "app_id"    => env("TEAM_APP_ID"),
            "set_id"    => env("TEAM_SET_ID"),
            "sender_id" => env("TEAM_SENDER_ID"),
            "users"     => [["user_id"=>$informUserId]],
            "is_notcare"=> true,
            "reply_opts"=> [["content"=>"好的"]]
        ];
        Queue::put("restapi",["post","inform","inform/send",$informData]);

        return $this::jsonResponse(false,$teamUserResult);
    }

    /**
     * @apiDescription 使用邀请码加入团队
     */
    public function joinwithcode(Request $request, $userId)
    {
        $input = $request->all();
        //参数检验
        $validator = Validator::make($input,
            [
                'invite_code'     => 'required|min:6'
            ]
        );
        if($validator->fails())
            return $this::jsonResponse(true,$validator->messages(),"paramError");

        $invite_code = $input["invite_code"];

        //检验邀请码
        $teamResult = DB::table("tm_team")->select("id","name","leader_id")
            ->where("invite_code",$invite_code)->where("is_deleted",false)->first();
        if(empty($teamResult))
            return $this::jsonResponse(true,[],"邀请码失效。");
        
        $teamId = $teamResult->id;

        //构造 发送给创始人 的通知
        $leaderId = $teamResult->leader_id;
        $teamName = $teamResult->name;
        $aInformData = [
            "title"     => "{{user:id:$userId:name}} 已通过邀请码加入 $teamName",
            "app_id"    => env("TEAM_APP_ID"),
            "set_id"    => env("TEAM_SET_ID"),
            "sender_id" => env("TEAM_SENDER_ID"),
            "users"     => [["user_id"=>$leaderId]],
            "is_notcare"=> true,
            "reply_opts"=> [["content"=>"好的"]]
        ];
        
        return $this->store($aInformData,$teamId,$userId);
    }

    /**
     * @apiDescription 成员申请加入
     */
    public function apply($teamId,$userId)
    {
        //添加关联
        $teamUserResult = DB::table("tm_team_user")
            ->select("id","token","state")
            ->where("team_id",$teamId)->where("user_id",$userId)
            ->where("is_deleted",false)->first();

        if(!empty($teamUserResult)){
            $teamUserId = $teamUserResult->id;
            $token      = $teamUserResult->token;
            if($teamUserResult->state == 1){
                return $this::jsonResponse(true,[],"您已加入此团队。");
            }else{
                DB::table("tm_team_user")->where("id",$teamUserId)->update(["state"=>0]);
            }
        }else{
            $token = md5($userId.time().str_random(6));
            $insertData = [
                "team_id"  =>$teamId,
                "user_id"  =>$userId,
                "token"    =>$token
            ];
            $teamUserId = DB::table("tm_team_user")->insertGetId($insertData);
        }

        //发送申请通知
        $teamName = DB::table("tm_team")->where("id",$teamId)->value("name");
        $leaderId = DB::table("tm_team")->where("id",$teamId)->value("leader_id");

        $informData = [
            "title"     => "{{user:id:$userId:name}} 申请加入 $teamName",
            "app_id"    => env("TEAM_APP_ID"),
            "set_id"    => env("TEAM_SET_ID"),
            "sender_id" => env("TEAM_SENDER_ID"),
            "close_trigger_type" => 1,
            "close_trigger_value"=> 1,
            "users"     =>[["user_id"=>$leaderId]],
            "is_urgent" =>false,
            "reply_opts"=>[
                ["content"=>"同意","url_hook"=>url("/api/team/$teamId/user/$userId/apply/agree?token=$token"),"is_expected"=>true],
                ["content"=>"拒绝","url_hook"=>url("/api/team/$teamId/user/$userId/apply/disagree?token=$token")]
            ]
        ];
        Queue::put("restapi",["post","inform","inform/send",$informData]);

        return $this::jsonResponse(false,$teamUserId);
    }

    /**
     * @apiDescription 同意成员加入申请
     */
    public function agreeApply(Request $request, $teamId,$userId)
    {
        $input = $request->all();
        $input["user_id"] = $userId;
        return $this->disOrAgree($teamId,$input,$disOr=false,$inviteOr=false);
    }

     /**
     * @apiDescription 拒绝成员加入申请
     */
    public function disagreeApply(Request $request, $teamId,$userId)
    {
        $input = $request->all();
        $input["user_id"] = $userId;
        return $this->disOrAgree($teamId,$input,$disOr=true,$inviteOr=false);
    }

    /**
     * @apiDescription 成员同意加入邀请
     */
    public function agreeInvite(Request $request, $teamId)
    {
        $input = $request->all();
        return $this->disOrAgree($teamId,$input,$disOr=false,$inviteOr=true);
    }

     /**
     * @apiDescription 成员拒绝加入邀请
     */
    public function disagreeInvite(Request $request, $teamId)
    {
        $input = $request->all();
        return $this->disOrAgree($teamId,$input,$disOr=true,$inviteOr=true);
    }

    public function disOrAgree($teamId,$input,$disOr,$inviteOr){
        //参数检验
        $validator = Validator::make($input,
            [
                'user_id'   => 'required|min:1',
                'token'     => 'required|min:6'
            ]
        );
        if($validator->fails())
            return $this::jsonResponse(true,$validator->messages(),"paramError");

        $userId = $input["user_id"];
        $token  = $input["token"];

        //申请记录
        $teamUserResult = DB::table("tm_team_user")->select("id")
            ->where("team_id",$teamId)->where("user_id",$userId)->where("token",$token)->first();

        if(!$teamUserResult)
            return $this::jsonResponse(true,[],"无此记录。");

        //构造 发送的 通知
        $teamName = DB::table("tm_team")->where("id",$teamId)->value("name");

        if($inviteOr){
            $leaderId = DB::table("tm_team")->where("id",$teamId)->pluck("leader_id");
            $title    = "{{user:id:$userId:name}} 已".($disOr?"拒绝":"同意")."加入 $teamName";
            $users    = [["user_id"=>$leaderId]];
        }else{
            $title    = "你被".($disOr?"拒绝":"同意")."加入 $teamName";
            $users    = [["user_id"=>$userId]];
        }

        $informData = [
        	"title" 	=> $title,
            "app_id"    => env("TEAM_APP_ID"),
            "set_id"    => env("TEAM_SET_ID"),
            "sender_id" => env("TEAM_SENDER_ID"),
        	"users"		=> $users,
        	"is_notcare"=> true,
            "reply_opts"=> [["content"=>"好的"]]
        ];

        if($disOr){
            $teamUserResult = DB::table("tm_team_user")
                ->where("id",$teamUserResult->id)
                ->update(["state"=>-1,"join_time"=>date("Y-m-d H:i:s")]);
            Queue::put("restapi",["post","inform","inform/send",$informData]);
            return $this::jsonResponse(false,$teamUserResult);
        }

        return $this->store($informData,$teamId,$userId);

    }


}
